<template>
  <div id="info" style="padding: 10px;">
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="50%"
      top="10%"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :modal-append-to-body="false"
    >
      <el-form ref="form" :model="submitForm" label-width="100px">
        <el-form-item label="批文名称" prop="mc" :rules="[{ required: true, message: '请输入批文名称', trigger: 'blur' }]">
          <el-input v-model="submitForm.mc" placeholder="请输入批文名称"/>
        </el-form-item>
        <el-form-item v-if="historyTableName === 'centreSyDwbd'" label="批文文号" prop="jgbzwh" :rules="[{ required: true, message: '请输入批文文号', trigger: 'blur' }]">
          <el-input v-model="submitForm.jgbzwh" placeholder="请输入批文文号"/>
        </el-form-item>
        <el-form-item v-if="historyTableName === 'centreDwbd'" label="批文文号" prop="pzwh" :rules="[{ required: true, message: '请输入批文文号', trigger: 'blur' }]">
          <el-input v-model="submitForm.pzwh" placeholder="请输入批文文号"/>
        </el-form-item>
        <el-form-item label="批准时间" prop="shijian" :rules="[{ required: true, message: '请选择批准时间', trigger: 'blur' }]">
          <el-date-picker
            v-model="submitForm.shijian"
            type="date"
            value-format="yyyy-MM-dd 00:00:00"
            placeholder="请选择批准时间"
          />
        </el-form-item>
        <el-form-item label="附件" prop="fileIds">
          <el-upload
            ref="uploadRef"
            :action="this.$http.defaults.baseURL+this.$http.defaults.headcountAPI+'api/genFileInfo/upload'"
            :on-success="handleUploadSucc"
            :on-error="uploadError"
            :before-upload="beforeUpload"
            accept="application/pdf,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document,application/vnd.ms-works,.wps"
            :file-list="fileList"
            :on-remove="handleRemove"
          >
            <el-button type="primary" :loading="btnLoading">上传</el-button>
          </el-upload>
        </el-form-item>
      </el-form>
      <div style="text-align: center; margin-top: 20px;">
        <el-button type="primary" :loading="btnLoading" @click="submit('form')">确定</el-button>
        <el-button @click="dialogVisible = false">取消</el-button>
      </div>
    </el-dialog>

    <el-scrollbar style="height: calc(100vh - 194px)">
      <div v-if="flag === 'user'" style="text-align: end; margin-bottom: 10px;">
        <el-button type="success" icon="el-icon-plus" @click="addData()">新增</el-button>
        <el-popconfirm
          title="确定批量删除所选信息吗？"
          @onConfirm="deleteData()"
          @confirm="deleteData()"
          style="margin-left: 10px;"
        >
          <el-button slot="reference" type="danger" class="filter-item" icon="el-icon-delete">批量删除</el-button>
        </el-popconfirm>
      </div>
      <section class="wboxd">
        <el-table
          ref="multipleTable"
          :data="listInfo"
          border
          highlight-current-row
          v-loading="listLoading"
          @selection-change="handleSelectionChange"
        >
          <el-table-column v-if="flag === 'user'" key="selection" align="center" type="selection" width="50px">
          </el-table-column>
          <el-table-column key="index" label="序号" align="center" type="index" width="50px">
          </el-table-column>
          <el-table-column key="mc" prop="mc" label="批文名称" align="center" width="400px">
            <template slot-scope="scope">
              <div style="text-align: left;">{{ scope.row.mc }}</div>
            </template>
          </el-table-column>
          <el-table-column v-if="historyTableName === 'centreSyDwbd'" key="jgbzwh" prop="jgbzwh" label="批文文号" align="center" width="140px" show-overflow-tooltip>
          </el-table-column>
          <el-table-column v-if="historyTableName === 'centreDwbd'" key="pzwh" prop="pzwh" label="批文文号" align="center" width="140px" show-overflow-tooltip>
          </el-table-column>
          <el-table-column key="shijian" prop="shijian" label="批准时间" align="center" width="100px">
            <template slot-scope="scope">
              <div>{{ fclsj(scope.row.shijian) }}</div>
            </template>
          </el-table-column>
          <el-table-column key="files" prop="files" label="附件" align="center">
            <template slot-scope="scope">
              <div v-for="item in scope.row.files" :key="'files_' + item.id" style="text-align: left;">
                <a href="javascript:;" @click="downloadFile(item.id)"><i class="el-icon-paperclip" />{{item.fileName}}.{{item.fileType}}</a>
              </div>
            </template>
          </el-table-column>
          <el-table-column v-if="flag === 'user'" key="handle" label="操作" align="center" width="160px">
            <template slot-scope="scope">
              <el-button type="primary" size="small" @click="editData(scope.row)">修改</el-button>
              <el-popconfirm
                title="确认要删除该信息吗"
                @onConfirm="deleteData(scope.row.dataId)"
                @confirm="deleteData(scope.row.dataId)"
              >
                <el-button slot="reference" size="small" type="danger">删除</el-button>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
      </section>
      <div class="block">
        <el-pagination style="float:right" :total="totalnum" :page-size="pageSize" @current-change="handleCurrentChange" :current-page="pageNum" @size-change="handleSizeChange" :page-sizes="[10, 20, 30, 50]" layout="total, sizes, prev, pager, next, jumper"></el-pagination>
      </div>
    </el-scrollbar>
  </div>
</template>

<script>
export default {
  name: 'DetailHistory',
  props: {
    jgsyCode: '',
    flag: '',
    historyTableName: ''
  },
  watch: {
    jgsyCode: {
      handler () {
        if (this.historyTableName) {
          this.getList()
        }
      },
      immediate: true
    }
  },
  data () {
    return {
      listLoading: false,
      pageNum: 1,
      pageSize: 10,
      totalnum: null,
      changeSizeFlag: false,
      listInfo: [],
      dialogTitle: '',
      dialogVisible: false,
      submitForm: {
        dataId: null,
        jgsyCode: '',
        mc: '',
        jgbzwh: '',
        pzwh: '',
        shijian: '',
        fileIds: []
      },
      fileList: [],
      btnLoading: false,
      multipleSelection: []
    }
  },
  methods: {
    // 获取列表
    getList () {
      const para = {
        pageNum: this.pageNum,
        pageSize: this.pageSize,
        jgsyCode: this.jgsyCode
      }
      this.listLoading = true
      this.$http
        .post(this.$http.defaults.headcountAPI + `api/${this.historyTableName}/queryByPage`, para)
        .then(response => {
          if (response.data.success) {
            this.listLoading = false
            this.listInfo = response.data.result.records
            this.totalnum = response.data.result.total
            this.changeSizeFlag = false
          } else {
            this.$message({
              message: '获取失败:' + response.data.message,
              type: 'error'
            })
            this.listLoading = false
          }
        })
        .catch(error => {
          this.$message({
            message: '网络获取失败:' + error,
            type: 'error'
          })
          this.listLoading = false
        })
    },
    handleSizeChange (val) {
      this.changeSizeFlag = true
      this.pageNum = 1
      this.pageSize = val
      this.getList()
    },
    handleCurrentChange (val) {
      if (this.changeSizeFlag === false) {
        this.pageNum = val
        this.getList()
      }
    },
    // 新增
    addData () {
      this.submitForm.dataId = null
      this.submitForm.jgsyCode = ''
      this.submitForm.mc = ''
      this.submitForm.jgbzwh = ''
      this.submitForm.pzwh = ''
      this.submitForm.shijian = ''
      this.submitForm.fileIds = []
      this.fileList = []
      this.dialogTitle = '新增'
      this.dialogVisible = true
    },
    // 编辑
    editData (row) {
      this.submitForm = {...row}
      const date = new Date(this.submitForm.shijian)
      this.submitForm.shijian = new Date(date.getFullYear(), date.getMonth(), date.getDate())
      this.fileList = []
      if (row.files) {
        row.files.forEach(item => {
          this.fileList.push({
            id: item.id,
            name: item.fileName + '.' + item.fileType
          })
        })
      }
      this.dialogTitle = '编辑'
      this.dialogVisible = true
    },
    // 提交
    submit (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          const para = {...this.submitForm}
          para.jgsyCode = this.jgsyCode
          para.shijian = new Date(para.shijian)
          para.fileIds = this.fileList.map(item => item.id)
          this.btnLoading = true
          this.$http
            .post(this.$http.defaults.headcountAPI + `api/${this.historyTableName}/save`, para)
            .then(response => {
              if (response.data.success === true) {
                this.btnLoading = false
                this.$message({
                  message: '操作成功',
                  type: 'success'
                })
                this.dialogVisible = false
                this.getList()
              } else {
                console.log('操作失败:' + response.data.message)
                this.$message({
                  message: '操作失败:' + response.data.message,
                  type: 'error'
                })
                this.btnLoading = false
              }
            })
            .catch(error => {
              console.log(error)
              this.btnLoading = false
            })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    // 批量删除
    handleSelectionChange (val) {
      this.multipleSelection = val
    },
    // 删除
    deleteData (id) {
      let ids = []
      if (id) {
        ids = [id]
      } else {
        ids = this.multipleSelection.map(item => item.dataId)
      }
      if (ids.length > 0) {
        this.$http
          .post(this.$http.defaults.headcountAPI + `api/${this.historyTableName}/remove`, { ids: ids })
          .then(response => {
            if (response.data.success === true) {
              this.$message({
                message: '删除成功',
                type: 'success'
              })
              this.getList()
            } else {
              console.log('删除失败:' + response.data.message)
              this.$message({
                message: '删除失败:' + response.data.message,
                type: 'error'
              })
            }
          })
          .catch(error => {
            console.log(error)
          })
      } else {
        this.$message({
          message: '请至少选择一条信息',
          type: 'danger'
        })
      }
    },
    // 上传
    handleUploadSucc (response, file, fileList) {
      this.btnLoading = false
      if (response.success) {
        const obj = response.result[0]
        this.fileList.push({
          id: obj.id,
          name: obj.fileName + '.' + obj.fileType
        })
        this.$message({
          message: '上传成功！' + response.message,
          type: 'success'
        })
      } else {
        this.$message({
          message: '上传失败:' + response.message,
          type: 'error'
        })
      }
    },
    handleRemove (file, fileList) {
      this.fileList = this.fileList.filter(item => item.id !== file.id)
    },
    beforeUpload (file) {
      const isFormat = file.name.indexOf('.docx') > 0 || file.name.indexOf('.doc') > 0 || file.name.indexOf('.pdf') > 0 || file.name.indexOf('.DOCX') > 0 || file.name.indexOf('.DOC') > 0 || file.name.indexOf('.PDF') > 0 || file.name.indexOf('.wps') > 0 || file.name.indexOf('.WPS') > 0
      const isLt500M = file.size / 1024 / 1024 < 60
      if (!isLt500M) {
        this.$message.error('单个附件不能超过60M!')
      } else {
        if (!isFormat) {
          this.$message.error('附件格式必须为word、pdf、wps!')
        } else {
          this.btnLoading = true
        }
      }
      return isFormat && isLt500M
    },
    uploadError (err) {
      this.btnLoading = false
      this.$message({
        message: '上传失败:' + err,
        type: 'error'
      })
    },
    // 下载
    downloadFile (id) {
      window.open(this.$http.defaults.baseURL + this.$http.defaults.headcountAPI + 'api/genFileInfo/download?id=' + id)
    },
    // 格式化日期
    fclsj (date) {
      var mydate = new Date(date)
      var year = mydate.getFullYear()
      var month = mydate.getMonth() + 1
      var d = mydate.getDate()
      return year + '.' + month + '.' + d
    }
  }
}
</script>
